package com.jxpanda.starter.wechat;

import com.jxpanda.starter.wechat.property.WechatProperties;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Collections;

/**
 * @author Panda
 */
@Configuration
@EnableConfigurationProperties(WechatProperties.class)
public class AutoConfiguration {

    @Bean
    @ConditionalOnProperty(prefix = WechatProperties.PREFIX, name = "merchant.enabled", havingValue = "true")
    public CloseableHttpClient wechatPayHttpClient(WechatProperties wechatProperties) {
        WechatProperties.Merchant merchant = wechatProperties.getMerchant();
        PrivateKey privateKey = merchant.loadPrivateKey();
        X509Certificate certificate = merchant.loadCertificate();
        WechatPay2Credentials credentials = new WechatPay2Credentials(merchant.getMchId(), new PrivateKeySigner(merchant.getCertificateSerialNumber(), privateKey));
        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(credentials, merchant.getApiV3Key().getBytes(StandardCharsets.UTF_8));
        return WechatPayHttpClientBuilder.create()
                .withMerchant(merchant.getMchId(), merchant.getCertificateSerialNumber(), privateKey)
                .withWechatpay(Collections.singletonList(certificate))
                .withValidator(new WechatPay2Validator(verifier))
                .build();
    }

    @Bean
    @ConditionalOnProperty(prefix = WechatProperties.PREFIX, name = "merchant.enabled", havingValue = "true")
    public AesUtil wechatAesUtil(WechatProperties wechatProperties) {
        return new AesUtil(wechatProperties.getMerchant().getApiV3Key().getBytes(StandardCharsets.UTF_8));
    }

    @Bean
    @ConditionalOnProperty(prefix = WechatProperties.PREFIX, name = "merchant.enabled", havingValue = "true")
    public WechatPayService wechatPayService() {
        return new WechatPayService();
    }

    @Bean
    public WechatUrlService wechatUrlService() {
        return new WechatUrlService();
    }

    @Bean
    public WechatService wechatService() {
        return new WechatService();
    }

}
